
package cz.czu.pef.DataModelling.utils;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


@Singleton
@Startup
public class SpringLoader
{

  private static final Logger logger = Logger.getLogger(SpringLoader.class.getName());

  private static ClassPathXmlApplicationContext basicApplicationContext = null;
  private static ClassPathXmlApplicationContext mainApplicationContext = null;

  @PostConstruct
  private void startup()
  {
    logger.log(Level.INFO, "startup():: Loading Spring context");
    synchronized (SpringLoader.class)
    {
      if (mainApplicationContext == null)
      {
        basicApplicationContext = new ClassPathXmlApplicationContext("/beanRefContext.xml");
        mainApplicationContext = (ClassPathXmlApplicationContext) basicApplicationContext.getBean("mainApplicationContext");
      }
    }
  }

  @PreDestroy
  private void shutdown()
  {
    try
    {
      logger.log(Level.INFO, "shutdown():: Destroying Spring context");

      if (mainApplicationContext != null)
        mainApplicationContext.close();
      mainApplicationContext = null;

      if (basicApplicationContext != null)
        basicApplicationContext.close();
      basicApplicationContext = null;
    }
    finally
    {
      logger.log(Level.INFO, "shutdown():: Spring context destroyed");
    }
  }

  public static ApplicationContext getContext()
  {
    return mainApplicationContext;
  }
}
